import { Toast } from "antd-mobile";
import { useEffect } from "react";
import Navbar from "../../compoents/Navbar";
// import { SideBar } from "antd-mobile";
import { useNavigate } from "react-router-dom";
// import {chinaRegions} from "./data";
import style from './index.module.css'
import { Aim } from '@react-vant/icons';
import Cityslice from '../../compoents/Cityslice/Index'
import { useDispatch, useSelector } from 'react-redux'
import { setCurrentCity } from '../../store/UseStateList'
import { useAMapLocation } from '../../utils/useAMapLocation'
import type { RootState } from '../../store/store'
function Index() {
  const navigate = useNavigate();
  // const [activeKey, setActiveKey] = useState("0");
  const dispatch = useDispatch();
  const currentCity = useSelector((state: RootState) => state.UseStateList.currentCity)
  const { city, province, district, loading, /* error, */ getLocation } = useAMapLocation()

  useEffect(() => {
    // 首次进入尝试定位，但不阻塞
    getLocation().then(res => {
      if (res) {
        const name = res.district || res.city || res.province || ''
        if (name) dispatch(setCurrentCity(name))
      }
    }).catch(() => {})
  }, [dispatch, getLocation])
  
  return (
    <div className={style.cityPage}>
      <div className={style.stickyHeader}>
        <Navbar title="选择城市" showBack onBack={() => navigate(-1)} >
          
        </Navbar>
      
      <div className={style.navabar} style={{ display:'flex'}}>
      <div className={style.pofwei} style={{display:'flex',width:'100%',justifyContent:'space-between',padding:'8px 0'}}>
        <span>当前定位:{(currentCity || city) ? `${province || ''}${city}${district ? ' · ' + district : ''}` : '定位中...'}</span>   
        
         <span className={style.xinxi} onClick={async()=>{
          try {
            const res = await getLocation();
            if (res) {
              const name = res.district || res.city || res.province || ''
              if (name) dispatch(setCurrentCity(name))
              Toast.show({ content: '已更新到当前城市：' + res.city })
            }
          } catch (e) {
            const msg = e instanceof Error ? e.message : '定位失败'
            Toast.show({ content: msg })
          }
        }}><Aim  style={{paddingTop:2}}/>{loading ? '定位中' : '刷新'}</span>
        </div>
      </div>
      </div>
      <div className={style.headerSpacer}></div>
      <Cityslice onSelect={(city)=>{ dispatch(setCurrentCity(city)); navigate(-1); }} />
    </div>
  );
}

export default Index;
